package com.lijiajia.cloud.authserver.service.impl.mongodb;

import com.lijiajia.cloud.authserver.pojo.mongodb.UserConnection;
import com.lijiajia.cloud.authserver.service.UserConnectionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 用户连接服务实现 mongo
 *
 * @author lijiajia
 * @since 2019-05-22
 */
@Slf4j
@Service
public class MongoUserConnectionService implements UserConnectionService {
	private MongoTemplate mongoTemplate;

	public MongoUserConnectionService(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}

	@Override
	public UserConnection insert(UserConnection userConnection) {
		return mongoTemplate.insert(userConnection);
	}

	@Override
	public Optional<Long> findMaxRank(String userId, String providerId) {
		Query query = BasicQuery.query(
			Criteria.where(UserConnection.USER_ID).is(userId)
				.and(UserConnection.PROVIDER_ID).is(providerId)
		);
		query.with(Sort.by(Sort.Direction.DESC, UserConnection.RANK));
		query.limit(1);
		Optional<UserConnection> connectionOptional = Optional.ofNullable(mongoTemplate.findOne(query, UserConnection.class));
		return connectionOptional.map(UserConnection::getRank);
	}
}
